package com.mew.mail.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.mapper.AccessoryMapper;
import com.mew.common.dc.mapper.MailMapper;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.enm.MailAccessoryType;
import com.mew.common.enm.MailStatusType;
import com.mew.common.enm.ZbmType;
import com.mew.common.entity.mail.Accessory;
import com.mew.common.entity.mail.Mail;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.mail.MailBO;
import com.mew.common.rest.mail.MailDetailInfoResponseMessage;
import com.mew.common.rest.mail.MailResponseMessage;
import com.mew.provide.RegisterFeignService;
import com.mew.user.service.FriendService;
import com.zebra.common.ZbmAreaType;
import com.zebra.common.ZbmMessage;
import com.zebra.common.event.EventBusAsyncCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author dylin
 * @create 2021/4/2
 */
@Service
public class MailService {
    @Autowired
    private MailMapper mailMapper;
    @Autowired
    private AccessoryMapper accessoryMapper;
    @Autowired
    private ProfileService profileService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private RegisterFeignService registerFeignService;

    /**
     *插入邮件
     * @param mail
     * @param accessory
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertMail(Mail mail, Accessory... accessory){
        mailMapper.insert(mail);
        for (Accessory a : accessory) {
            a.setMailId(mail.getId());
            accessoryMapper.insert(a);
        }
        registerFeignService.zbmCommon(ZbmMessage.builder()
                .zbmType(ZbmType.MAIL.code())
                .zbmArea(ZbmAreaType.Person.code())
                .userIds(new long[]{mail.getReceiveUser()})
                .build());
    }

    /**
     * 领取邮件
     * @param userId
     * @param mailId
     * @return
     */
    public int receiveAward(long userId,int mailId){
        Mail mail = mailMapper.selectById(mailId);
        if(mail==null||mail.getReceiveUser() != userId){
            return ResponseCode.ParamInvalid.code();
        }
        if(mail.getStatus() != MailStatusType.Unread.code() && mail.getStatus()!=MailStatusType.Read.code()){
            return ResponseCode.MailReceived.code();
        }
        QueryWrapper<Accessory> queryWrapper=new QueryWrapper();
        queryWrapper.eq("mail_id",mailId);
        List<Accessory> list = accessoryMapper.selectList(queryWrapper);
        for (Accessory accessory : list) {
            int type=accessory.getType();
            if(type==MailAccessoryType.Gold.code()){
                profileService.doGold(userId,accessory.getQuantity(), GoldProcessType.parse(mail.getType()));
                if (GoldProcessType.Tran.code() == mail.getType()){
                    EventBusAsyncCenter.post(userId); //调用 策略----判断是 转账才计算------
                }
            }else if(type==MailAccessoryType.Jewel.code()){
                profileService.doGold(userId,0,accessory.getQuantity(),0.0,mail.getType());
            }
        }
        mail.setStatus(MailStatusType.Receive.code());
        mailMapper.updateById(mail);
        return ResponseCode.Success.code();
    }

    /**
     * 阅读邮件
     */
    public void read(int mailId){
        mailMapper.update(Mail.builder().status(MailStatusType.Read.code()).build(),
                new LambdaUpdateWrapper<Mail>().eq(Mail::getId,mailId).eq(Mail::getStatus,MailStatusType.Unread));
    }

    /**
     * 获取邮件列表
     * @param userId
     * @return
     */
    public MailResponseMessage getMailList(long userId){
        List<MailBO> mailList = mailMapper.getMailList(userId);
        // 2021 -8-10  策划修改方案。这里的代码修改进具体信息里
        /*//这里特殊处理不同邮件的res
        for (MailBO mailBO : mailList) {
            //好友赠送  看能否回赠
            if(mailBO.getType()==GoldProcessType.Friend.code()){
                mailBO.setRes(friendService.isGiveRep(mailBO.getReceiveUser(),mailBO.getSendUser())?0:1);
            }
        }*/
        return MailResponseMessage.builder().mailList(mailList).build();
    }

    /**
     * 获取未读邮件数量
     * @return
     */
    public Integer getMailCount(long userId){
        return mailMapper.selectCount(new LambdaQueryWrapper<Mail>()
                .eq(Mail::getReceiveUser, userId)
                .eq(Mail::getStatus, 0)
                .ge(Mail::getSendTime, LocalDateTime.now().plusDays(-6))
        );
    }

    public MailDetailInfoResponseMessage getDetailInfo(int mailId){
        MailDetailInfoResponseMessage detailInfo = mailMapper.getDetailInfo(mailId);
        //这里特殊处理不同邮件的res
        //好友赠送  看能否回赠
        if(detailInfo.getType() == GoldProcessType.Friend.code()){
            detailInfo.setRes(friendService.isGiveRep(detailInfo.getSendUserId(),detailInfo.getSendUserId())?0:1);
        }
        read(mailId);
        return mailMapper.getDetailInfo(mailId);
    }
}
